package net.hserver.apm.plugin.filter;

import ch.qos.logback.classic.spi.LoggingEvent;
import cn.hserver.core.interfaces.LogAdapter;
import cn.hserver.core.ioc.annotation.Bean;
import cn.hserver.core.queue.HServerQueue;
import cn.hserver.core.server.context.ConstConfig;
import cn.hserver.core.server.context.HServerContextHolder;
import cn.hserver.core.server.context.Webkit;
import cn.hserver.core.server.util.PropUtil;
import net.hserver.apm.common.DataConfig;
import net.hserver.apm.common.entity.LogInfo;

@Bean
public class ApmLogFilter implements LogAdapter {

    private final static Boolean isLog = PropUtil.getInstance().getBoolean("amp.log");

    @Override
    public void log(LoggingEvent loggingEvent) throws Exception {
        if (isLog) {
            Webkit webKit = HServerContextHolder.getWebKit();
            if (webKit != null) {
                String requestId = webKit.httpRequest.getRequestId();
                LogInfo logInfo = new LogInfo();
                logInfo.setAppName(ConstConfig.APP_NAME);
                logInfo.setChainId(requestId);
                logInfo.setLevel(loggingEvent.getLevel().levelStr);
                logInfo.setMessage(loggingEvent.getFormattedMessage());
                logInfo.setThreadName(loggingEvent.getThreadName());
                logInfo.setTime(loggingEvent.getTimeStamp());
                StringBuilder stringBuilder = new StringBuilder();
                StackTraceElement[] callerData = loggingEvent.getCallerData();
                for (int i = 0; i < callerData.length; i++) {
                    StackTraceElement callerDatum = callerData[i];
                    stringBuilder.append(callerDatum.toString());
                    if (i < callerData.length - 1) {
                        stringBuilder.append("->");
                    }
                }
                logInfo.setStackTrace(stringBuilder.toString());
                HServerQueue.sendQueue("APM_SEND", DataConfig.APM_DATA_LOG_INFO, logInfo);
            }
        }
    }
}
